<?php

namespace app\common\util;

use framework\library\Logger;
use yii\data\Pagination;
use yii\helpers\ArrayHelper;

/**
 * 公共方法类
 * @package app\common\util
 * @author 莫东肖
 * @version 1.3
 * @date 2020-10-24 新增PageData
 */
class ResultTable
{
    /**
     * table 全部数据假分页
     * */
    public function commonPage($input, $result)
    {
        $total = count($result['table_list']);
        $table_list = array_slice($result['table_list'], ($input['page'] - 1) * $input['page_size'], $input['page_size']);

        return [
            'page' => $input['page'], // 当前页
            'page_size' => $input['page_size'],  // 每页显示的条数
            'count' => ceil($total / $input['page_size']),  //总页数
            'total' => $total, // 总条数
            'head_list' => $result['head_list'],
            'table_list' => $table_list,
        ];
    }

    /**
     * 头信息组合
     * */
    public function head_list($head_list, $sort_array = [])
    {
        $data = [];
        foreach ($head_list as $field => $field_name) {
            $temp = [
                'field' => $field,
                'field_name' => $field_name,
            ];
            if ($sort_array && in_array($field, $sort_array)) {
                $temp['sort'] = true;
            } elseif ($sort_array) {
                $temp['sort'] = false;
            }
            $data[] = $temp;
        }

        return $data;
    }

    /**
     * table 字段排序
     * */
    public function commonFieldSort($input, $result)
    {
        // 无排序
        if (empty($input['field']) || !in_array($input['sort'], ['SORT_ASC', 'SORT_DESC'])) {
            return $result;
        }
        $sort = SORT_ASC;
        if ($input['sort'] == 'SORT_DESC') {
            $sort = SORT_DESC;
        }
        ArrayHelper::multisort($result['table_list'], $input['field'], $sort, SORT_NUMERIC);

        return $result;
    }

    /**
     * excel table下载
     * */
    public function commonDown($result)
    {
        $excel = [];

        // 头部信息（有效头部字段）
        $temp = [];
        foreach ($result['head_list'] as $value) {
            $temp[$value['field']] = $value['field_name'];
        }
        $excel[] = $temp;

        foreach ($result['table_list'] as $value) {
            $tmp = [];
            // 过滤多余字段 字段顺序纠正
            foreach ($temp as $key => $v) {
                if (isset($value[$key])) {
                    $tmp[$key] = $value[$key];
                } else {
                    $tmp[$key] = '';
                }
            }
            $excel[] = $tmp;
        }

        return $excel;
    }

    /**
     * @name 带分页格式化数据功能
     * @param object $query 查询数据
     * @param $page 分页 默认1
     * @param int $limit 分页数量 默认20
     * @example
     *  示例一：  $model = (new ClassImportHeadModel())->find()->orderBy('id ASC')->select(['*']);
     *  示例二：  $model = (new ClassImportHeadModel())->find();
     *  调用：    $data = $this->PageData($model, $input['page'], $input['page_size']);
     * */
    public function PageData($query, $page = 1, $page_size = 100)
    {
        $sTime = microtime(true);

        $countQuery = clone $query;
        $total = $countQuery->count();
        $pages = new Pagination([
            'totalCount' => $total,
            'pageSize' => $page_size,
            'validatePage' => false, // page超过最大页数不进行处理
        ]);
        $pages->setPage($page - 1); // 设置分页
        $query = $query->offset($pages->offset)->limit($pages->limit);
        // 生成sql
        $sql = $query->createCommand()->getRawSql();
        // 数据查询
        $data = $query->asArray()->all();
        // 对象转换为数组
        $pagecount = $pages->getPageCount();
        $currentpage = $pages->getPage() + 1;
        // 记录sql信息
        $consume = (int)(round(microtime(true) - $sTime, 3) * 1000);
        Logger::sql(['info' => $sql, 'consume' => $consume]);

        return [
            'page' => (int)$currentpage, // 当前页
            'page_size' => (int)$page_size, // 设置分页数量
            'count' => (int)$pagecount, // 分页总数
            'total' => (int)$total, // 数据总数
            'table_list' => $data, // 数据
        ];
    }

    /**
     * 弃用 请使用 PageData() 方法
     * @name 带分页格式化数据功能
     * @param object $query 查询数据
     * @param $page 分页 默认1
     * @param int $limit 分页数量 默认20
     * @example
     *  示例一：  $model = (new ClassImportHeadModel())->find()->orderBy('id ASC')->select(['*']);
     *  示例二：  $model = (new ClassImportHeadModel())->find();
     *  调用：    $data = $this->PageArray($model, $input['page'], $input['page_size']);
     */
    public function PageArray($query, $page = 1, $page_size = 20)
    {
        $countQuery = clone $query;

        $total = $countQuery->count();
        $pages = new Pagination([
            'totalCount' => $total,
            'pageSize' => $page_size,
            'validatePage' => false, // page超过最大页数不进行处理
        ]);
        $pages->setPage($page - 1); // 设置分页
        $query = $query->offset($pages->offset)->limit($pages->limit);
        // 记录sql
        $sql = $query->createCommand()->getRawSql();
        Logger::sql($sql);
        // 数据查询
        $data = $query->asArray()->all();

        // 对象转换为数组
        $pagecount = $pages->getPageCount();
        $currentpage = $pages->getPage() + 1;

        return [
            'page' => $currentpage, // 当前页
            'page_size' => $page_size, // 设置分页数量
            'count' => $pagecount, // 分页总数
            'total' => $total, // 数据总数
            'table_list' => $data, // 数据
        ];
    }
}
